package com.hzdl.car.controller;

import com.github.pagehelper.PageInfo;
import com.hzdl.car.bean.CarRentInfo;
import com.hzdl.car.bean.Customer;
import com.hzdl.car.service.CarRentInfoService;
import com.hzdl.car.util.AJAXResult;
import com.hzdl.car.util.CustomExcelUtil;
import com.hzdl.car.util.RentExcelUtil;
import com.hzdl.car.vo.CarRentInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@Controller
@RequestMapping("/carRentInfo")
public class CarRentInfoController {

    @Autowired
    private CarRentInfoService cris;

    @RequestMapping("/carRentInfoInit")
    public String carRentInfoInit(){
        return "/system/rentInfoManager";
    }
    @RequestMapping("/carRentInfoShow")
    @ResponseBody
    public AJAXResult carRentInfoShow(CarRentInfoVo carRentInfoVo){
        if(carRentInfoVo.getPage()==null){
            carRentInfoVo.setPage(1);
        }
        if(carRentInfoVo.getLimit()==null){
            carRentInfoVo.setLimit(5);
        }
        PageInfo pageInfo=cris.findByWhere(carRentInfoVo);
        return new AJAXResult(0,"",pageInfo.getList(),pageInfo.getTotal());
    }
    @RequestMapping("/rentInfoUpdate")
    @ResponseBody
    public AJAXResult rentInfoUpdate(CarRentInfoVo carRentInfoVo){
        int row=cris.carRentInfo(carRentInfoVo);
        if(row==0){
            return AJAXResult.UPDATE_ERROR;
        }
        return AJAXResult.UPDATE_SUCCESS;
    }

    @RequestMapping("/exportRentInfo")
    public ResponseEntity<Object> exportRentInfo(String rentid) {
        CarRentInfo carRentInfo = cris.findByRentId(rentid);
        Customer customer = cris.findCustnameByIdentity(carRentInfo.getIdentity());
        carRentInfo.setCustname(customer.getCustname());
        ByteArrayOutputStream stream = RentExcelUtil.createExcelByRent(carRentInfo,"czd-templet.xls");
        String fileName = null;
        //导出文件名称
        try {
            fileName = URLEncoder.encode("客户信息.xls", "UTF-8");
        } catch (
                UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //设置下载是的头部响应对象
        HttpHeaders httpHeader = new HttpHeaders();
        httpHeader.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        httpHeader.setContentDispositionFormData("attachment", fileName);

        return new ResponseEntity<Object>(stream.toByteArray(), httpHeader, HttpStatus.CREATED);
    }
}
